(function($) {
	$.zgallery = function(zgallery_settings) {
		zgallery_settings = jQuery.extend({
			hook: 'rel', /* the attribute tag to use for zgallery hooks. default: 'rel'. For HTML5, use "data-rel" or similar. */
			animation_speed: 'fast', /* fast/slow/normal */
			ajaxcallback: function() {},
			slideshow: 5000, /* false OR interval time in ms */
			autoplay_slideshow: false, /* true/false */
			opacity: 0.80, /* Value between 0 and 1 */
			show_title: true, /* true/false */
			allow_resize: true, /* Resize the photos bigger than viewport. true/false */
			allow_expand: true, /* Allow the user to expand a resized image. true/false */
			default_width: 500,
			default_height: 344,
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			horizontal_padding: 0, /* The padding on each side of the picture */
			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over zgallery */
			wmode: 'opaque', /* Set the flash wmode attribute */
			autoplay: true, /* Automatically start videos: True/False */
			modal: false, /* If set to true, only the close button will close the window */
			deeplinking: true, /* Allow zgallery to update the url to enable deeplinking. */
			overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
			overlay_gallery_max: 30, /* Maximum number of pictures in the overlay gallery */
			keyboard_shortcuts: true, /* Set to false if you open forms inside zgallery */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){}, /* Called when zgallery is closed */
			ie6_fallback: true,
			widthComment: 260,
			widthMinPicture: 688,
			heightMinPicture: 439,
			widthPictureFull: 800,
			heightPictureFull: 800,
			id_photo: 12,
			fullSize: 0,
			id_zgallery_album: 1,
			gallery_markup: '',
			markup: '<div class="zgallery_pic_holder" id="zGalleryPhoto"> \
				<div class="zgallery_content_container"> \
			<div class="zgallery_left"> \
			<div class="zgallery_right"> \
				<div class="zgallery_content"> \
					<div class="zgallery_loaderIcon"></div> \
					<div class="zgallery_fade"> \
						<a href="#" class="zgallery_expand" title="Expand the image">Expand</a> \
						<div class="zgallery_hoverContainer"> \
							<a class="zgallery_next" href="#">next</a> \
							<a class="zgallery_expandFull" href="#">next</a> \
							<a class="zgallery_previous" href="#">previous</a> \
						</div> \
						<div id="zgallery_full_res"></div> \
						<div class="zgallery_details" id="zgallery_details"> \
							<div class="zgallery_nav"> \
								<div class="zinfoPhotoLike"> \
									<div class="zinfoPhotoImageLike"> </div> \
									<a href="" class="zgallery_like"></a> \
									<div class="zinfo_gallery_like"></div> \
								</div> \
								<p class="currentTextHolderNumber"></p> \
								<p class="currentTextHolder"></p> \
								<div class="zinfoPhoto"> \
								<div class="zinfoPhotoLikeTitle"> \
								<span href="" class="zgallery_nb_like_title">Like:</span> \
								<span href="" class="zgallery_nb_like"></span> \
								</div> \
								<div class="zinfoPhotoViewTitle"> \
								<span href="" class="zgallery_nb_view_title">View:</span> \
								<span href="" class="zgallery_nb_view"></span> \
								</div> \
								</div> \
							</div> \
						</div> \
					</div> \
				</div> \
			</div> \
			</div> \
		</div> \
		<div class="zgallery_bottom"> \
		</div> \
	</div> \
	<div class="zgallery_overlay" id="zgallery_overlay"></div> \
	<div class="zgallery_info" id="zgallery_info" style="display:none;"> \
	</div>',
			image_markup: '<img id="fullResImage" src="{path}" />',
			image_expand: '<img id="fullExpandImage" src="{path}" />',
			flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
			quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
			iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
			inline_markup: '<div class="zgallery_inline">{content}</div>',
			custom_markup: '',
			social_tools: '<div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="//www.facebook.com/plugins/like.php?locale=en_US&href={location_href}&amp;layout=button_count&amp;show_faces=true&amp;width=500&amp;action=like&amp;font&amp;colorscheme=light&amp;height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div>' /* html or false to disable */
		}, zgallery_settings);
		
		// Global variables accessible only by zgallery
		var percentBased = false, zgallery_dimensions, zgallery_open,
		
		// zgallery container specific
		zgallery_contentHeight, zgallery_contentWidth, zgallery_containerHeight, zgallery_containerWidth,
		
		// Window size
		windowHeight = $(window).height(), windowWidth = $(window).width(),

		// Global elements
		zgallery_slideshow;
		
		doresize = true, scroll_pos = _get_scroll();
		
	
		// Window/Keyboard events
		$(window).unbind('resize.zgallery').bind('resize.zgallery',function(){ _center_overlay(); _resize_overlay(); });
		
		if(zgallery_settings.keyboard_shortcuts) {
			$(document).unbind('keydown.zgallery').bind('keydown.zgallery',function(e){
				if(typeof $zgallery_pic_holder != 'undefined'){
					if($zgallery_pic_holder.is(':visible')){
						switch(e.keyCode){
							case 37:
								$.zgallery.changePage('previous');
								e.preventDefault();
								break;
							case 39:
								$.zgallery.changePage('next');
								e.preventDefault();
								break;
						};
					};
				};
			});
		};
		
		/**
		* Initialize zgallery.
		*/
		$.zgallery.initialize = function() {
			settings = zgallery_settings;
			
			// Define where in the array the clicked item is positionned
 			
			zgallery_images = new Array ();
			zgallery_titles = new Array ();
			zgallery_descriptions = new Array ();
			id_zgallery_photo = new Array ();
			allow_like = new Array ();
			number_view = new Array ();
			number_like = new Array (); 
			nameAlbum = '';
			set_position=0; 					//	set_position = settings.position;
			$.ajax({
				type: 'GET',
				url: baseDir + 'modules/zgallery/zgallery-ajax.php',
				async: false,
				data: 'getInfos=1&id='+settings.id_zgallery_album,
				success: function(strings) {
					var datas = $.parseJSON(strings);
					for (var i=0;i<datas.length;i++){
						zgallery_images.push(datas[i].linkImage);
						zgallery_titles.push(datas[i].name);
						zgallery_descriptions.push(datas[i].description);
						id_zgallery_photo.push(datas[i].id_zgallery_photo);
						allow_like.push (datas[i].allowLike);
						number_view.push (datas[i].nb_view);
						number_like.push (datas[i].nb_like);
						if (settings.id_photo==datas[i].id_zgallery_photo)
							set_position=i;
					}
				}
			});
			
			/*Get name album increa view*/
			$.ajax({
				type: 'GET',
				url: baseDir + 'modules/zgallery/zgallery-ajax.php',
				async: false,
				data: 'getInfosAlbum=1&id='+settings.id_zgallery_album+'&id_photo='+id_zgallery_photo[set_position],
				success: function(strings) {
					nameAlbum = strings; 
				}
			});
			
			$.ajax({
				type: 'GET',
				url: baseDir + 'modules/zgallery/zgallery-ajax.php',
				async: false,
				data: 'getViewPhoto=1&id='+settings.id_zgallery_album+'&id_photo='+id_zgallery_photo[set_position],
				success: function(strings) {
					 if (strings=='ok')
						 number_view[set_position]++;
				}
			});
			
			
			// Build the overlay {this} being the caller
			_build_overlay(); 
			
			if(settings.allow_resize)
				$(window).bind('scroll.zgallery',function(){ _center_overlay(); });
			
			$.zgallery.open();
			
			return false;
		}


		/**
		* Opens the zgallery modal box.
		* @param image {String,Array} Full path to the image to be open, can also be an array containing full images paths.
		* @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
		* @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions.
		*/
		$.zgallery.open = function(event) {
			if($.browser.msie && $.browser.version == 6) $('select').css('visibility','hidden'); // To fix the bug with IE select boxes

			_checkPosition($(zgallery_images).size()); // Hide the next/previous links if on first or last images.
		
			$('.zgallery_loaderIcon').show();
		
			// Fade the content in
			if($ppt.is(':hidden')) $ppt.css('opacity',0).show();
			
			// Display the current position
			$zgallery_pic_holder.find('.currentTextHolderNumber').text((set_position+1) + settings.counter_separator_label + $(zgallery_images).size());
			$zgallery_pic_holder.find('.currentTextHolder').text(nameAlbum);
			// Set the description
			if(typeof zgallery_descriptions[set_position] != 'undefined' && zgallery_descriptions[set_position] != ""){
				$zgallery_pic_holder.find('.zgallery_description').show().html(unescape(zgallery_descriptions[set_position]));
			}else{
				$zgallery_pic_holder.find('.zgallery_description').hide();
			}
			
			/** 
			 * Display like
			 */
			$_allowLike = allow_like[set_position];
			$nb_like = number_like[set_position];
			$nb_view = number_view[set_position];
			$zgallery_pic_holder.find('.zgallery_nb_like').html($nb_like);
			$zgallery_pic_holder.find('.zgallery_nb_view').html($nb_view);
			$zgallery_pic_holder.find('.zinfo_gallery_like').html('');
			if ($_allowLike==1) {
				$zgallery_pic_holder.find('.zgallery_like').html('Like');
			}
			if ($_allowLike==0) {
				$zgallery_pic_holder.find('.zgallery_like').html('');
				$zgallery_pic_holder.find('.zinfo_gallery_like').html('Liked');
				$zgallery_pic_holder.find('.zgallery_nb_like').html($nb_like);
				$zgallery_pic_holder.find('.zinfo_gallery_like').removeAttr('id');
			} else if ($_allowLike==2 || $_allowLike==4) {
				$zgallery_pic_holder.find('.zgallery_like').html('');
				$zgallery_pic_holder.find('.zinfo_gallery_like').html('Like');
				$zgallery_pic_holder.find('.zgallery_nb_like').html($nb_like);
				$zgallery_pic_holder.find('.zinfo_gallery_like').removeAttr('id');
			} else if ($_allowLike==3) {
				$zgallery_pic_holder.find('.zgallery_like').html('');
				$zgallery_pic_holder.find('.zinfo_gallery_like').html('Like');
				$zgallery_pic_holder.find('.zgallery_nb_like').html($nb_like);
				$zgallery_pic_holder.find('.zinfo_gallery_like').attr('id','zinfo_gallery_like_limit');
				$zgallery_pic_holder.find('#zinfo_gallery_like_limit').click(function(){
					alert ("This photo has enough like");
				});
			}
			
			// Fade the holder
			$zgallery_pic_holder.fadeIn(function(){
				
				imgPreloader = "";
				skipInjection = false;
				
				// Inject the proper content
				if (zgallery_images.length>0) {
					switch(_getFileType(zgallery_images[set_position])){
						case 'image':
							imgPreloader = new Image();
							// Preload the neighbour images
							nextImage = new Image();
							if(set_position < $(zgallery_images).size() -1) nextImage.src = zgallery_images[set_position + 1];
							prevImage = new Image();
							if( zgallery_images[set_position - 1]) prevImage.src = zgallery_images[set_position - 1];
	
							$zgallery_pic_holder.find('#zgallery_full_res')[0].innerHTML = settings.image_markup.replace(/{path}/g,zgallery_images[set_position]);
							
							imgPreloader.onload = function(){
								// Fit item to viewport
								zgallery_dimensions = _fitToViewport(imgPreloader.width,imgPreloader.height);
								_showContent();
							};
	
							imgPreloader.onerror = function(){
								
								zgallery_dimensions = _fitToViewport(500,500);
								_showContent();
							};
							
							imgPreloader.src = zgallery_images[set_position];
						break;
					};
				}
				else 
					$.zgallery.close();
				if(!imgPreloader && !skipInjection){
					$zgallery_pic_holder.find('#zgallery_full_res')[0].innerHTML = toInject;
					// Show content
					_showContent();
				};
			});

			return false;
		};

	
		/**
		* Change page in the zgallery modal box
		* @param direction {String} Direction of the paging, previous or next.
		*/
		$.zgallery.changePage = function(direction){
			currentGalleryPage = 0;
			
			if(direction == 'previous') {
				set_position--;
				if (set_position < 0) set_position = $(zgallery_images).size()-1;
				$.ajax({
					type: 'GET',
					url: baseDir + 'modules/zgallery/zgallery-ajax.php',
					async: false,
					data: 'getViewPhoto=1&id='+settings.id_zgallery_album+'&id_photo='+id_zgallery_photo[set_position],
					success: function(strings) {
						 if (strings=='ok')
							 number_view[set_position]++;
					}
				});
			}else if(direction == 'next'){
				set_position++;
				/*Get view photo increace view*/
				
				if(set_position > $(zgallery_images).size()-1) set_position = 0;
				$.ajax({
					type: 'GET',
					url: baseDir + 'modules/zgallery/zgallery-ajax.php',
					async: false,
					data: 'getViewPhoto=1&id='+settings.id_zgallery_album+'&id_photo='+id_zgallery_photo[set_position],
					success: function(strings) {
						 if (strings=='ok')
							 number_view[set_position]++;
					}
				});
			}else{
				set_position=direction;
			};
			
			rel_index = set_position;

			if(!doresize) doresize = true; // Allow the resizing of the images
			if(settings.allow_expand) {
				$('.zgallery_contract').removeClass('zgallery_contract').addClass('zgallery_expand');
			}
			_hideContent(function(){ $.zgallery.open(); });
		};

		/**
		* Change gallery page in the zgallery modal box
		* @param direction {String} Direction of the paging, previous or next.
		*/
		$.zgallery.changeGalleryPage = function(direction){
			if(direction=='next'){
				currentGalleryPage ++;

				if(currentGalleryPage > totalPage) currentGalleryPage = 0;
			}else if(direction=='previous'){
				currentGalleryPage --;

				if(currentGalleryPage < 0) currentGalleryPage = totalPage;
			}else{
				currentGalleryPage = direction;
			};
			
			slide_speed = (direction == 'next' || direction == 'previous') ? settings.animation_speed : 0;

			slide_to = currentGalleryPage * (itemsPerPage * itemWidth);

			$zgallery_gallery.find('ul').animate({left:-slide_to},slide_speed);
		};

		/**
		* Closes zgallery.
		*/
		$.zgallery.close = function(){
			if($zgallery_overlay.is(":animated")) return;
			
			$zgallery_pic_holder.stop().find('object,embed').css('visibility','hidden');
			
			$('div.zgallery_pic_holder,div.ppt,.zgallery_fade').fadeOut(settings.animation_speed,function(){ $(this).remove(); });
			
			$zgallery_overlay.fadeOut(settings.animation_speed, function(){
				if($.browser.msie && $.browser.version == 6) $('select').css('visibility','visible'); // To fix the bug with IE select boxes
				
				if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','visible'); // Show the flash
				
				$(this).remove(); // No more need for the zgallery markup
				
				$(window).unbind('scroll.zgallery');
				
				clearHashtag();
				
				settings.callback();
				
				doresize = true;
				
				zgallery_open = false;
				
				delete settings;
			});
		};
	
		/**
		* Set the proper sizes on the containers and animate the content in.
		*/
		function _showContent(){
			$('.zgallery_loaderIcon').hide();

			// Calculate the opened top position of the pic holder
			projectedTop = scroll_pos['scrollTop']+3;
			if(projectedTop < 0) projectedTop = 0;

			$ppt.fadeTo(settings.animation_speed,1);
			var a=settings.widthMinPicture,b=settings.heightMinPicture;
			
			$.ajax({
				type: 'GET',
				url: baseDir + 'modules/zgallery/zgallery-ajax.php',
				async: true,
				data: 'comment=1&id='+id_zgallery_photo[set_position]+'&token='+static_token,
				success: function(data) {
					$zgallery_pic_holder.find('.zgallery_bottom').show().html(data);
					$('.zlistCommentsDiv').css({'max-height': b-100+'px'});
				}
			});
			// Resize the content holder
			$zgallery_pic_holder.find('.zgallery_content')
				.animate({
					height:b,
					width:a
				},settings.animation_speed);
			
			// Resize picture the holder
			$zgallery_pic_holder.animate({
				width:a
			},settings.animation_speed,function(){
				// seting size of picture
				$('.ppt').css({'width': a+'px'});
				$magicPicture = zgallery_dimensions['containerHeight'] / zgallery_dimensions['containerWidth'];
				$magicSize = settings.heightMinPicture / settings.widthMinPicture;
				$zgallery_pic_holder.find('.zgallery_hoverContainer').height(b).width(a);
				if (zgallery_dimensions['containerWidth'] < settings.widthMinPicture) {
					$('#fullResImage').css({'max-width': zgallery_dimensions['containerWidth']+'px'});
				}
				else {	
					$('#fullResImage').css({'max-width': a+'px'});
				}
				if (zgallery_dimensions['containerHeight'] < settings.heightMinPicture) {
					var paddingTop = b/2-zgallery_dimensions['containerHeight']/2;
					$('#fullResImage').css({'padding-top': paddingTop+'px'});
					$('#fullResImage').css({'max-height': zgallery_dimensions['containerHeight']+'px'});
					
				}else  {
					if ($magicPicture < $magicSize) {
						height = (settings.widthMinPicture *$magicPicture ); 
						paddingTop = (settings.heightMinPicture - height)/2;
						$('#fullResImage').css({'padding-top': paddingTop+'px'});
					}
					$('#fullResImage').css({'max-height': b+'px'});
				}
				$zgallery_pic_holder.find('#zgallery_full_res').height(b).width(a);
				
				$('a.zgallery_expand').show();
				
				$zgallery_pic_holder.find('.zgallery_content_container').width(a);
				
				$zgallery_pic_holder.find('.zgallery_fade').fadeIn(settings.animation_speed); // Fade the new content
				// size for comment
				
				$('.zgallery_bottom').css({'width': settings.widthComment+'px','height': b-10+'px','margin-left': a+'px'});
				
				// Show the nav
				if( _getFileType(zgallery_images[set_position])=="image") { $zgallery_pic_holder.find('.zgallery_hoverContainer').show(); }else{ $zgallery_pic_holder.find('.zgallery_hoverContainer').hide(); }
			
				
				if(settings.autoplay_slideshow && !zgallery_slideshow && !zgallery_open) $.zgallery.startSlideshow();
				
				settings.changepicturecallback(); // Callback!
				
				zgallery_open = true;
			});
			
			_insert_gallery();
			zgallery_settings.ajaxcallback();
		};
		
		/**
		* Hide the content...DUH!
		*/
		function _hideContent(callback){
			// Fade out the current picture
			$zgallery_pic_holder.find('#zgallery_full_res object,#zgallery_full_res embed').css('visibility','hidden');
			$zgallery_pic_holder.find('.zgallery_fade').fadeOut(settings.animation_speed,function(){
				$('.zgallery_loaderIcon').show();
				
				callback();
			});
		};
	
		/**
		* Check the item position in the gallery array, hide or show the navigation links
		* @param setCount {integer} The total number of items in the set
		*/
		function _checkPosition(setCount){
			(setCount >= 1) ? $('.zgallery_nav').show() : $('.zgallery_nav').hide(); // Hide the bottom nav if it's not a set.
		};
	
		/**
		* Resize the item dimensions if it's bigger than the viewport
		* @param width {integer} Width of the item to be opened
		* @param height {integer} Height of the item to be opened
		* @return An array containin the "fitted" dimensions
		*/
		function _fitToViewport(width,height){
			resized = false;
			
			_getDimensions(width,height);
			
			// Define them in case there's no resize needed
			imageWidth = width, imageHeight = height;

			if( ((zgallery_containerWidth > windowWidth) || (zgallery_containerHeight > windowHeight)) && doresize && settings.allow_resize && !percentBased) {
				resized = true, fitting = false;
				
				while (!fitting){
					if((zgallery_containerWidth > windowWidth)){
						imageWidth = (windowWidth - 50);
						imageHeight = (height/width) * imageWidth;
					}else if((zgallery_containerHeight > windowHeight)){
						imageHeight = (windowHeight - 50);
						imageWidth = (width/height) * imageHeight;
					}else{
						fitting = true;
					};
					zgallery_containerHeight = imageHeight, zgallery_containerWidth = imageWidth;
				};
				
				_getDimensions(imageWidth,imageHeight);
				
				if((zgallery_containerWidth > windowWidth) || (zgallery_containerHeight > windowHeight)){
					_fitToViewport(zgallery_containerWidth,zgallery_containerHeight)
				};
			};
			
			return {
				width:Math.floor(imageWidth),
				height:Math.floor(imageHeight),
				containerHeight:Math.floor(zgallery_containerHeight),
				containerWidth:Math.floor(zgallery_containerWidth) + (settings.horizontal_padding * 2),
				contentHeight:Math.floor(zgallery_contentHeight),
				contentWidth:Math.floor(zgallery_contentWidth),
				resized:resized
			};
		};
		
		/**
		* Get the containers dimensions according to the item size
		* @param width {integer} Width of the item to be opened
		* @param height {integer} Height of the item to be opened
		*/
		function _getDimensions(width,height){
			width = parseFloat(width);
			height = parseFloat(height);
			var a = settings.widthMinPicture;
			
			// Get the details height, to do so, I need to clone it since it's invisible
			$zgallery_details = $zgallery_pic_holder.find('.zgallery_details');
			$zgallery_details.width(a);
			$zgallery_pic_holder.find('.zgallery_nav').width(a);
			
			detailsHeight = parseFloat($zgallery_details.css('marginTop')) + parseFloat($zgallery_details.css('marginBottom'));
			
			$zgallery_details = $zgallery_details.clone().addClass(settings.theme).width(width).appendTo($('body')).css({
				'position':'absolute',
				'top':-10000
			});
			detailsHeight += $zgallery_details.height();
			detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details
			if($.browser.msie && $.browser.version==7) detailsHeight+=8;
			$zgallery_details.remove();
			
			// Get the titles height, to do so, I need to clone it since it's invisible
			$zgallery_title = $zgallery_pic_holder.find('.ppt');
			$zgallery_title.width(width);
			titleHeight = parseFloat($zgallery_title.css('marginTop')) + parseFloat($zgallery_title.css('marginBottom'));
			$zgallery_title = $zgallery_title.clone().appendTo($('body')).css({
				'position':'absolute',
				'top':-10000
			});
			titleHeight += $zgallery_title.height();
			$zgallery_title.remove();
			
			// Get the container size, to resize the holder to the right dimensions
			zgallery_contentHeight = height;
			zgallery_contentWidth = width;
			zgallery_containerHeight = zgallery_contentHeight;
			zgallery_containerWidth = width;
		}
	
		function _getFileType(itemSrc){
			return 'image';
		};
	
		function _center_overlay(){
			if(doresize && typeof $zgallery_pic_holder != 'undefined') {
				scroll_pos = _get_scroll();
				contentHeight = $zgallery_pic_holder.height(), contentwidth = $zgallery_pic_holder.width();

				projectedTop = scroll_pos['scrollTop']+3;
				if(projectedTop < 0) projectedTop = 0;
				
				if(contentHeight > windowHeight)
					return;

			};
		};
	
		function _get_scroll(){
			if (self.pageYOffset) {
				return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
			} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
				return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
			} else if (document.body) {// all other Explorers
				return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
			};
		};
	
		function _resize_overlay() {
			windowHeight = $(window).height(), windowWidth = $(window).width();
			
			if(typeof $zgallery_overlay != "undefined") $zgallery_overlay.height($(document).height()).width(windowWidth);
		};
	
		function _insert_gallery(){
			if( settings.overlay_gallery && _getFileType(zgallery_images[set_position])=="image" && (settings.ie6_fallback && !($.browser.msie && parseInt($.browser.version) == 6))) {
				itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin.
				navWidth = (settings.theme == "facebook" || settings.theme == "zgallery_default") ? 50 : 30; // Define the arrow width depending on the theme
				var a=settings.widthMinPicture;
				
				itemsPerPage = Math.floor((a - 100 - navWidth) / itemWidth);
				itemsPerPage = (itemsPerPage < zgallery_images.length) ? itemsPerPage : zgallery_images.length;
				totalPage = Math.ceil(zgallery_images.length / itemsPerPage) - 1;

				// Hide the nav in the case there's no need for links
				if(totalPage == 0){
					navWidth = 0; // No nav means no width!
					$zgallery_gallery.find('.zgallery_arrow_next,.zgallery_arrow_previous').hide();
				}else{
					$zgallery_gallery.find('.zgallery_arrow_next,.zgallery_arrow_previous').show();
				};

				galleryWidth = itemsPerPage * itemWidth;
				fullGalleryWidth = zgallery_images.length * itemWidth;
				
				// Set the proper width to the gallery items
				$zgallery_gallery
					.css('margin-left',-((galleryWidth/2) + (navWidth/2)))
					.find('div:first').width(galleryWidth+5)
					.find('ul').width(fullGalleryWidth)
					.find('li.selected').removeClass('selected');
				
				goToPage = (Math.floor(set_position/itemsPerPage) < totalPage) ? Math.floor(set_position/itemsPerPage) : totalPage;

				$.zgallery.changeGalleryPage(goToPage);
				
				$zgallery_gallery_li.filter(':eq('+set_position+')').addClass('selected');
			}else{
				$zgallery_pic_holder.find('.zgallery_content').unbind('mouseenter mouseleave');
				// $zgallery_gallery.hide();
			}
		}
	
		function _build_overlay(){
			// Inject Social Tool markup into General markup
			if(settings.social_tools)
				facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href)); 

			settings.markup = settings.markup.replace('{zgallery_social}',''); 
			
			$('#center_column').append(settings.markup); // Inject the markup
			
			$zgallery_pic_holder = $('.zgallery_pic_holder') , $ppt = $('.ppt'), $zgallery_overlay = $('div.zgallery_overlay'); // Set my global selectors
			
			// Inject the inline gallery!
			if(settings.overlay_gallery) {
				currentGalleryPage = 0;
				toInject = "";
				for (var i=0; i < zgallery_images.length; i++) {
					if(!zgallery_images[i].match(/\b(jpg|jpeg|png|gif)\b/gi)){
						classname = 'default';
						img_src = '';
					}else{
						classname = '';
						img_src = zgallery_images[i];
					}
					toInject += "<li class='"+classname+"'><a href='#'><img src='" + img_src + "' width='50' alt='' /></a></li>";
				};
				
				toInject = settings.gallery_markup.replace(/{gallery}/g,toInject);
				
				$zgallery_pic_holder.find('#zgallery_full_res').after(toInject);
				
				$zgallery_gallery = $('.zgallery_pic_holder .zgallery_gallery'), $zgallery_gallery_li = $zgallery_gallery.find('li'); // Set the gallery selectors

				$zgallery_gallery.find('.zgallery_arrow_next').click(function(){
					$.zgallery.changeGalleryPage('next');
					$.zgallery.stopSlideshow();
					return false;
				});
				
				$zgallery_gallery.find('.zgallery_arrow_previous').click(function(){
					$.zgallery.changeGalleryPage('previous');
					$.zgallery.stopSlideshow();
					return false;
				});
				
				
				
				
				$zgallery_pic_holder.find('.zgallery_content').hover(
					function(){
						$zgallery_pic_holder.find('.zgallery_details').fadeIn();
						$zgallery_pic_holder.find('.zgallery_expand').fadeIn();
						
					},
					function(){
						$zgallery_pic_holder.find('.zgallery_details').fadeOut();
						$zgallery_pic_holder.find('.zgallery_expand').fadeOut();
					});

				itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin.
				$zgallery_gallery_li.each(function(i){
					$(this)
						.find('a')
						.click(function(){
							$.zgallery.changePage(i);
							$.zgallery.stopSlideshow();
							return false;
						});
				});
			};
			
			$zgallery_pic_holder.attr('class','zgallery_pic_holder ' + settings.theme); // Set the proper theme

			/*Click Like*/
			$('a.zgallery_close').bind('click',function(){ $.zgallery.close(); return false; });

			$('a.zgallery_like').bind('click',function(){
				$.ajax({
					type: 'GET',
					url: baseDir + 'modules/zgallery/zgallery-ajax.php',
					async: true,
					data: 'like=1&id='+id_zgallery_photo[set_position]+'&id_album='+settings.id_zgallery_album,
					success: function(data) {
						data = data.split(",");
						if (data[3]==1) 
							alert ("Bạn không đủ điểm để like.");
						if (data[0]=='like') {
							$zgallery_pic_holder.find('.zgallery_nb_like').html(data[1]);
							$zgallery_pic_holder.find('.zgallery_like').html('');
							$zgallery_pic_holder.find('.zinfo_gallery_like').html('Liked');
							$zgallery_pic_holder.find('.zinfo_gallery_like').removeAttr('id');
							allow_like[set_position]=0;
							number_like[set_position]=data[1];
							if (data[2]==1) 
								alert ("Bạn đã được vào danh sách Lucky Member");
						}else {
//							$zgallery_pic_holder.find('.zgallery_nb_like').html(data[1]);
							$zgallery_pic_holder.find('.zgallery_like').html('Like');
						}
					}
				}); 
				return false;
			});

			if(settings.allow_expand) {
				$('a.zgallery_expand,a.zgallery_expandFull').bind('click',function(e){
					var width = zgallery_dimensions['containerWidth'],height = zgallery_dimensions['containerHeight'];
					
					if (width > windowWidth-10) {
						width = windowWidth-10;
					}
					if (height > windowHeight-10){
						height = windowHeight-10;
					}
					
					projectedTop = scroll_pos['scrollTop'] + ((windowHeight/2) - (zgallery_dimensions['containerHeight']/2));
					if (projectedTop<0)
						projectedTop=0;
					$('#zgallery_overlay').html('<a title="Expand the image" class="zgallery_unexpand" href="#" style="display: inline;">Expand</a>'+settings.image_expand.replace(/{path}/g,zgallery_images[set_position]));
					$('#fullExpandImage').css ({
						'max-height':height,
						'max-width':width,
						'margin-top':projectedTop
					});
					
					$zgallery_overlay
					.css({
						'opacity':1,
						'height':$(document).height(),
						'width':$(window).width(),
						'display': 'block',
						'z-index': 30000
						})
					.bind('click',function(){
						$zgallery_overlay.css({
							'opacity':0,
							'height':0,
							'width':0,
							'display': 'none'
							})
						$('#zgallery_overlay').html("");
					});
					return false;
				});
			}
		
			$zgallery_pic_holder.find('.zgallery_previous, .zgallery_nav .zgallery_arrow_previous').bind('click',function(){
				$.zgallery.changePage('previous');
				return false;
			});
		
			$zgallery_pic_holder.find('.zgallery_next, .zgallery_nav .zgallery_arrow_next').bind('click',function(){
				$.zgallery.changePage('next');
				return false;
			});
			
			_center_overlay(); // Center it
		};

		if(!zgallery_alreadyInitialized && getHashtag()){
			zgallery_alreadyInitialized = true;
			
			// Grab the rel index to trigger the click on the correct element
			hashIndex = getHashtag();
			hashRel = hashIndex;
			hashIndex = hashIndex.substring(hashIndex.indexOf('/')+1,hashIndex.length-1);
			hashRel = hashRel.substring(0,hashRel.indexOf('/'));

			// Little timeout to make sure all the zgallery initialize scripts has been run.
			// Useful in the event the page contain several init scripts.
			setTimeout(function(){ $("a["+zgallery_settings.hook+"^='"+hashRel+"']:eq("+hashIndex+")").trigger('click'); },50);
		}
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return $.zgallery.initialize(); 
	};
	
	function getHashtag(){
		url = location.href;
		hashtag = (url.indexOf('#zgallery') !== -1) ? decodeURI(url.substring(url.indexOf('#zgallery')+1,url.length)) : false;

		return hashtag;
	};
	
	function setHashtag(){
		if(typeof theRel == 'undefined') return; // theRel is set on normal calls, it's impossible to deeplink using the API
		location.hash = theRel + '/'+rel_index+'/';
	};
	
	function clearHashtag(){
		if ( location.href.indexOf('#zgallery') !== -1 ) location.hash = "zgallery";
	}
	
	function getParam(name,url){
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  return ( results == null ) ? "" : results[1];
	}
	function explode (delimiter, string, limit) {
	    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
	    // 
	    // version: 1109.2015
	    // discuss at: http://phpjs.org/functions/explode    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +     improved by: kenneth
	    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +     improved by: d3x
	    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // *     example 1: explode(' ', 'Kevin van Zonneveld');
	    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
	    // *     example 2: explode('=', 'a=bc=d', 2);
	    // *     returns 2: ['a', 'bc=d']
	    var emptyArray = {        0: ''
	    };
	 
	    // third argument is not required
	    if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {        return null;
	    }
	 
	    if (delimiter === '' || delimiter === false || delimiter === null) {
	        return false;    }
	 
	    if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
	        return emptyArray;
	    } 
	    if (delimiter === true) {
	        delimiter = '1';
	    }
	     if (!limit) {
	        return string.toString().split(delimiter.toString());
	    }
	    // support for limit argument
	    var splitted = string.toString().split(delimiter.toString());    var partA = splitted.splice(0, limit - 1);
	    var partB = splitted.join(delimiter.toString());
	    partA.push(partB);
	    return partA;
	}
	
	
})(jQuery);

var zgallery_alreadyInitialized = false; // Used for the deep linking to make sure not to call the same function several times.

